package io.jft.doll.tcp.utils

import kotlin.experimental.and

object BytesUtil {
    fun bytesToHexString(src: ByteArray?, length: Int): String? {
        if (src == null || src.isEmpty()) return null
        val stringBuilder = StringBuilder("")
        for (i in 0 until length) stringBuilder.append(String.format("%02X ", src[i] and 0xFF.toByte()))
        return stringBuilder.toString()
    }

    /**
     * Convert hex string to byte[]
     * @param hexString the hex string
     * @return byte[]
     */
    fun hexStringToBytes(hexString: String?): ByteArray? {
        if (hexString == null || hexString == "") {
            return null
        }
        val upperCaseHexString = hexString.toUpperCase()
        val length = upperCaseHexString.length / 2
        val hexChars = upperCaseHexString.toCharArray()
        val d = ByteArray(length)
        for (i in 0 until length) {
            val pos = i * 2
            d[i] = (charToByte(hexChars[pos]) shl 4 or charToByte(hexChars[pos + 1])).toByte()
        }
        return d
    }

    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private fun charToByte(c: Char): Int {
        return "0123456789ABCDEF".indexOf(c)
    }
}
